package com.atguigu.gulimall.cart.interceptor;

/**
 * @author 孤风雪影
 * @date 2021/1/18
 */

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.cart.to.UserInfoTo;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 在执行目标方法之前,判断用户的登录状态,并封装传递给controller目标请求
 */
@Component
public class CartInterceptor implements HandlerInterceptor {

    //ThreadLocal,在当前线程共享数据
    public final static ThreadLocal<UserInfoTo> userInfoToThreadLocal = new ThreadLocal<>();

    /**
     * 目标方法执行之前，封装临时用户user-key
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //线程中共享的用户信息
        UserInfoTo userInfoTo = new UserInfoTo();

        //判断是否登录
        HttpSession session = request.getSession();
        MemberRespVo loginUser = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (loginUser != null) {
            //用户登录了,设置userId
            userInfoTo.setUserId(loginUser.getId());
        }

        //是否有临时用户cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                //user-key
                String name = cookie.getName();
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)) {
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setHasTempCookie(true);
                }
            }
        }

        //如果没有临时用户,一定分配一个临时用户
        if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
            userInfoTo.setHasTempCookie(false);
        }

        //目标方法执行之前,在线程中放入共享数据,拦截器是线程的起点,后续任务都可以访问共享数据
        CartInterceptor.userInfoToThreadLocal.set(userInfoTo);

        return true;
    }

    /**
     * 业务执行之后,分配临时用户,让浏览器保存Cookie
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        UserInfoTo userInfoTo = CartInterceptor.userInfoToThreadLocal.get();

        if (!userInfoTo.getHasTempCookie()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("shopifymall.cn");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CartInterceptor.userInfoToThreadLocal.remove();
    }
}
